package com.mingke.java.Normal;

import java.io.IOException;
import java.net.Socket;

/**
 * @author mingke
 * @function 读写请求的处理器
 * @date 2021/11/8
 */
public class NormalSocketHandler extends Thread {
    //内部维护的Socket对象
    private NormalSocketClient socketClient;

    public NormalSocketHandler(Socket socket) {
        try {
            socketClient = new NormalSocketClient(socket);
        }catch (Exception e) {
            e.printStackTrace();
        }
        //设置全局的客户端id，方便查验
        socketClient.setCid(NormalSocketServer.cidNum++);
        //将全局id发送给Socket客户端
        try {
            socket.getOutputStream().write(Integer.valueOf(String.valueOf(socketClient.getCid())));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        //循环监听客户端的信息
        while((socketClient.getSocket()!=null)&&(socketClient.getSocket().isConnected())) {
            try {
                int bufferLength = socketClient.getInputStream().available();
                //如果存在数据，就进行解析
                if(bufferLength > 0) {
                    System.out.println(Thread.currentThread().getName()+"线程缓冲区大小："+bufferLength);
                    byte bytes[] = new byte[bufferLength];
                    if(socketClient.getInputStream().read(bytes) != -1) {
                        //数据读取成功
                        System.out.println("数据内容");
                        for(int i = 0; i < bufferLength; i++) {
                            if(i == bufferLength-1) {
                                System.out.print(bytes[i] + "\n");
                            }else {
                                System.out.print(bytes[i] + " ");
                            }
                        }
                    }else {
                        //数据读取失败
                        System.out.println("数据读取失败");
                    }
                }else {
                    System.out.println("没有数据呢");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //如果客户端断开，则释放目前所用的资源
        try {
            socketClient.getInputStream().close();
            socketClient.getOutputStream().close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(socketClient.getCid()+"号客户端断开连接，资源释放完成");
    }
}
